import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'

const api = {
  version: process.versions.electron,
  saveFile: (data) => {
    ipcRenderer.send('save-file', data)
  },
  getVersion: () => {
    return ipcRenderer.invoke('get-version')
  },
  newOpen: (params: any) => {
    return ipcRenderer.invoke('new-open', params)
  },
  copyToClipboard: (text: string) => {
    ipcRenderer.invoke('copy-text-to-clipboard', text)
  },
  updateSoftware: (url: string) => {
    return ipcRenderer.invoke('update-software', url)
  },
  downloadUpdate: (params: any) => {
    return ipcRenderer.invoke('download-update', params)
  },
  setWallpaper: (params: any) => {
    return ipcRenderer.invoke('set-wallpaper', params)
  },
  //将事件传递给渲染进程,渲染进程通过window访问
  onUpdateStorage: (callback: (event: Electron.IpcRendererEvent, ...args: any[]) => void) => {
    ipcRenderer.on('update-storage', callback)
  }
}


if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  // @ts-ignore (define in dts)
  window.electron = electronAPI
  // @ts-ignore (define in dts)
  window.api = api
}
